package com.uenpay.im;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.os.AsyncTask;
import android.os.RemoteException;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.baidu.mapapi.SDKInitializer;
import com.qiyunxin.android.http.HttpInvokeResultCode;
import com.qiyunxin.android.http.QiYunXinHttpApplication;
import com.qiyunxin.android.http.listener.OnHttpRequestTextListener;
import com.qiyunxin.android.http.net.HttpInvokeItem;
import com.qiyunxin.android.http.net.HttpRequestAsyncTaskQueue;
import com.qiyunxin.android.http.net.HttpRequestType;
import com.qiyunxin.android.http.net.HttpTextAsyncTask;
import com.qiyunxin.android.http.utils.Utils;
import com.qyx.android.activity.QiYunXinApplication;
import com.qyx.android.entity.FriendEntity;
import com.qyx.android.protocol.BaseContentModel;
import com.qyx.android.protocol.SendMsgCallBack;
import com.qyx.android.protocol.SessionModel;
import com.qyx.android.weight.QiYunxinWeightApplication;
import com.qyx.android.weight.utils.baidumap.BaiduLoacationUtil;
import com.qyx.android.weight.view.MyToast;
import com.uenpay.im.callback.OnGetAllClassmate;
import com.uenpay.im.configuration.QYXIMConfiguration;
import com.uenpay.im.invokeitems.friends.GetFriends;
import com.uenpay.im.invokeitems.login.RegOrCancelDeviceNoInvokeItem;
import com.uenpay.im.panel.emoji.QyxEmoji;
import com.uenpay.im.ui.old.activity.PushServiceConn;
import com.uenpay.smallvideo.VCamera;

import java.util.ArrayList;

/**
 * CopyRight:
 * <p/>
 * Class Explain:
 *
 * @author
 * @Create Date: 2014-9-20 13:45:29
 * @copyRight http://www.qiyunxin.com
 */
public class IMApplication extends QiYunXinApplication {

    private static final String TAG = "MyApplication";

    public final String WX_APPID = "wx5230cf11c729e362";
    /**
     * app名称
     */
    public static final String appName = "weifubao";
    /**
     * 是否刷新会话首页数据(默认刷新)
     */
    public static boolean IS_REFRESH_TOP_MSG = true;
    /**
     * 是否刷新通讯录
     */
    public static boolean IS_GET_ALL_FRIENDS = true;
    public static MyToast toast;
    /**
     * 定位相关
     */
    private BaiduLoacationUtil mBaiduLoacationUtil;
    /**
     * 全局变量引用实例
     */
    private static IMApplication mApplication = null;
    /**
     * 保存所有类名的集合
     */
    public ArrayList<Activity> activityList = new ArrayList<Activity>();

    /**
     * 通知数量
     **/
    public static int notification_sum = 0;
    /**
     * 聊天消息列表
     **/
    public static QYXIMConfiguration config;
    public static boolean is_have_network = false;
    /**
     * 消息广播接收器
     **/
    private MsgReceiver msgReceiver;

    /**
     * 记录当前显示的页面
     **/
    public static enum PAGE {
        PAGE_NULL, PAGE_TALK, PAGE_TALK_DETAIL, PAGE_LOCKE_SCREEN
    }

    ;

    public static Context getAppContext() {
        return IMApplication.appContext;
    }

    /**
     * 发送消息
     *
     * @param message         消息Model
     * @param sessionModel    会话Model
     * @param sendMsgCallBack 发送消息回调
     * @return
     */
    public int sendMessage(BaseContentModel message, SessionModel sessionModel, SendMsgCallBack sendMsgCallBack) {
        try {
            IS_REFRESH_TOP_MSG = true;
            if (PushServiceConn.getInstance(appContext).pushService == null) {
                PushServiceConn.getInstance(appContext).connPushService();
                return 0;
            }
            return PushServiceConn.getInstance(appContext).pushService.sendMessage(message, sessionModel, sendMsgCallBack);
        } catch (RemoteException e) {
            e.printStackTrace();
            return 0;
        }
    }

    /**
     * 广播监听
     *
     * @author SL
     */
    public class MsgReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(Intent.ACTION_TIME_TICK) || action.equals(Intent.ACTION_SCREEN_ON)) {
                PushServiceConn.getInstance(appContext).startChatService();
            } else if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
                is_have_network = Utils.isNetworkConnected(IMApplication.getAppContext());
            } else if (action.equals(BroadcastAction.RESTART_APP_ACTION)) {
                PushServiceConn mPushServiceConn = new PushServiceConn(getApplicationContext());
                mPushServiceConn.connPushService();
            }
        }
    }

    @Override
    public void onCreate() {
        /** 百度地图SDK **/
        SDKInitializer.initialize(this);
        toast = MyToast.makeText(getBaseContext(), "", MyToast.LENGTH_SHORT);
        toast.setGravity(Gravity.BOTTOM, 0, 100);
        mApplication = this;
        appContext = getApplicationContext();
        String app_name = getCurProcessName(appContext);
        /** 设置包名 **/
        setAppPackageName(getPackageName());
        /** 设置APP名称 **/
        setAppName(app_name);
        /** 初始化数据库 **/
        initDB();
        /** 设置开发模式，主要用于是否打印日志 **/
        setDevelopModel(true);
        /** 是否将打印的日志写入SD卡中 **/
        setWriteLogToSDCard(false);
        /**
         * 初始化网络请求
         *
         * @Parameters: applicationName APP名称 mApplication Context
         */
        QiYunXinHttpApplication.getInstance().initData(getPackageName(), this);

        if (app_name != null && app_name.indexOf(":push") > -1) {
            super.onCreate();
            return;
        } else {
            String cust_id = getCustId();
            config = new QYXIMConfiguration(cust_id);
        }
        QyxEmoji emoji = new QyxEmoji();
        QiYunxinWeightApplication.getInstance().initData(this, emoji._texts, emoji._resourceId);
        super.onCreate();
        /** 注册系统广播 **/
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Intent.ACTION_TIME_TICK);
        intentFilter.addAction(Intent.ACTION_LOCALE_CHANGED);
        intentFilter.addAction(Intent.ACTION_SCREEN_ON);
        intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        intentFilter.addAction(BroadcastAction.RESTART_APP_ACTION);

        if (msgReceiver == null) {
            msgReceiver = new MsgReceiver();
            registerReceiver(msgReceiver, intentFilter);
        }
        PushServiceConn.getInstance(appContext).startChatService();
        initSmallVideo(getAppContext());
    }

    public String getCurProcessName(Context context) {
        int pid = android.os.Process.myPid();
        ActivityManager mActivityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningAppProcessInfo appProcess : mActivityManager.getRunningAppProcesses()) {
            if (appProcess.pid == pid) {
                return appProcess.processName;
            }
        }
        return null;
    }

    public static IMApplication getInstance() {
        if (mApplication == null) {
            mApplication = new IMApplication();
        }
        return mApplication;
    }

    /**
     * 获取百度地理位置工具实例
     *
     * @return
     */
    public BaiduLoacationUtil GetBaiduLoacationUtil() {
        if (mBaiduLoacationUtil == null) {
            mBaiduLoacationUtil = BaiduLoacationUtil.getInstance(getAppContext());
        }
        return mBaiduLoacationUtil;
    }

    public static void showToast(String s) {
        View toastRoot = LayoutInflater.from(appContext).inflate(R.layout.toast_layout, new LinearLayout(getAppContext()), false);
        TextView content = (TextView) toastRoot.findViewById(R.id.toast_content);
        content.setText(s);
        toast.setGravity(Gravity.TOP, 0, 220);
        if (toast != null) {
            toast.setView(toastRoot);
            toast.show();
        }
    }

    public static void showToast(int s) {
        View toastRoot = LayoutInflater.from(appContext).inflate(R.layout.toast_layout, new LinearLayout(getAppContext()), false);
        TextView content = (TextView) toastRoot.findViewById(R.id.toast_content);
        content.setText(s);
        toast.setGravity(Gravity.TOP, 0, 220);
        if (toast != null) {
            toast.setView(toastRoot);
            toast.show();
        }
    }

    public static boolean getFirstTime() {
        SharedPreferences setting = appContext.getSharedPreferences("account_config", 0);
        return setting.getBoolean("firsttime", true);
    }

    public static void setFirstTime() {
        SharedPreferences setting = appContext.getSharedPreferences("account_config", 0);
        SharedPreferences.Editor editor = setting.edit();
        editor.putBoolean("firsttime", false);
        editor.apply();
    }

    public static boolean getIsLogoutConfig() {
        SharedPreferences setting = appContext.getSharedPreferences("account_config", 0);
        return setting.getBoolean("is_logout", true);
    }

    public static void setIsLogoutConfig(boolean is_logout) {
        SharedPreferences setting = appContext.getSharedPreferences("account_config", 0);
        SharedPreferences.Editor editor = setting.edit();
        editor.putBoolean("is_logout", is_logout);
        editor.commit();
    }

    /**
     * 设置登录信息
     *
     * @param cust_id    登录用户cust_id
     * @param token      登录用户token
     *                   <p/>
     *                   每次登录时都必须设置token和cust_id
     * @param login_auth talk service 认证
     */
    public void setLoginInfo(String cust_id, String token, String login_auth) {
        setCustId(cust_id);
        setAccessToken(token);
        setAccessAuth(login_auth);
        SharedPreferences setting = appContext.getSharedPreferences("account_config", 0);
        SharedPreferences.Editor editor = setting.edit();
        if (token != null) {
            editor.putString("token", token);
        }
        editor.putString("cust_id", cust_id);
        editor.commit();

        config = new QYXIMConfiguration(cust_id);
        initDB();
        try {
            if (PushServiceConn.getInstance(appContext).pushService != null) {
                PushServiceConn.getInstance(appContext).pushService.regRecvMsgCallback(getCustId(), getAccessToken(), getAccessAuth());
            }
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取登录auth
     *
     * @return
     */
    public static String getAccessAuth() {
        SharedPreferences setting = appContext.getSharedPreferences("account_config", 0);
        return setting.getString("login_auth", "");
    }

    /**
     * 设置登录auth
     *
     * @param login_auth
     */

    public void setAccessAuth(String login_auth) {
        SharedPreferences setting = appContext.getSharedPreferences("account_config", 0);
        SharedPreferences.Editor editor = setting.edit();
        editor.putString("login_auth", login_auth);
        editor.commit();
    }

    public static String getAccessToken() {
        SharedPreferences setting = appContext.getSharedPreferences("account_config", 0);
        return setting.getString("token", "");
    }

    private void setAccessToken(String accessToken) {
        SharedPreferences setting = appContext.getSharedPreferences("account_config", 0);
        SharedPreferences.Editor editor = setting.edit();
        editor.putString("token", accessToken);
        editor.commit();
    }

    /**
     * 获取ucrtoken
     *
     * @return
     */
    public String getUcrtoken() {
        SharedPreferences setting = appContext.getSharedPreferences("account_config", 0);
        return setting.getString("ucrtoken", "");
    }

    /**
     * 设置ucrtoken
     *
     * @param ucrtoken
     */
    public void setUcrToken(String ucrtoken) {
        SharedPreferences setting = appContext.getSharedPreferences("account_config", 0);
        SharedPreferences.Editor editor = setting.edit();
        editor.putString("ucrtoken", ucrtoken);
        editor.commit();
    }

    /**
     * ucropenid
     *
     * @return
     */
    public String getUcrOpendId() {
        SharedPreferences setting = appContext.getSharedPreferences("account_config", 0);
        return setting.getString("ucropenid", "");
    }

    /**
     * 设置ucrtoken
     *
     * @param ucropenid
     */
    public void setUcrOpenId(String ucropenid) {
        SharedPreferences setting = appContext.getSharedPreferences("account_config", 0);
        SharedPreferences.Editor editor = setting.edit();
        editor.putString("ucropenid", ucropenid);
        editor.commit();
    }

    public static String getUserMobilePhone() {
        SharedPreferences setting = appContext.getSharedPreferences("account_config", 0);
        return setting.getString("mobile_phone", "");
    }

    public static void setUserMobilePhone(String mobile_phone) {
        SharedPreferences setting = appContext.getSharedPreferences("account_config", 0);
        SharedPreferences.Editor editor = setting.edit();
        editor.putString("mobile_phone", mobile_phone);
        editor.commit();
    }

    /**
     * 获取所有联系人
     *
     * @param onGetAllClassmate
     */
    public static void getAllClassmate(final OnGetAllClassmate onGetAllClassmate) {
        IMApplication.config.setFriendLastUpdateId(0);
        GetFriends item = new GetFriends(IMApplication.config.getFriendLastUpdateId());

        HttpRequestAsyncTaskQueue.getInstance().AddTask(new HttpTextAsyncTask(item).SetRequestType(HttpRequestType.SERVER_ONLY),
                new OnHttpRequestTextListener() {

                    @Override
                    public void OnSuccess(HttpInvokeItem item, boolean isCache, String cacheFilePath) {
                        GetFriends.getAllFriendResult result = ((GetFriends) item).getOutput();
                        if (result != null && result.status == HttpInvokeResultCode.RESULT_OK) {
                            Log.d(TAG, result.friends.toString());
                            saveFriendsRemarkName(result.friends);
                            onGetAllClassmate.onSucceeful(result);
                        }
                    }

                    @Override
                    public void OnProgress(long total_bytes, long downloaded_bytes) {

                    }

                    @Override
                    public void OnFail(boolean isCache, String reason) {
                        Log.d(TAG, reason);
                    }
                });

    }

    /**
     * 保存我的好友的备注名称
     *
     * @param friends
     */
    private static void saveFriendsRemarkName(ArrayList<FriendEntity> friends) {
        if (friends == null || friends.size() < 1) {
            return;
        }
        for (int i = 0, size = friends.size(); i < size; i++) {
            new SaveFreindsRemarkNameAsyncTask(friends.get(i).cust_id, friends.get(i).remarks_name).execute();
        }
    }

    /**
     * 保存好友备注
     *
     * @author SL
     */
    private static class SaveFreindsRemarkNameAsyncTask extends AsyncTask<Void, Void, Void> {
        String remark_name = "";
        String cust_id = "";

        public SaveFreindsRemarkNameAsyncTask(String _cust_id, String _remark_name) {
            remark_name = _remark_name;
            cust_id = _cust_id;
        }

        @Override
        protected Void doInBackground(Void... arg0) {
            IMApplication.config.setFriendsRemarkName(cust_id, remark_name);
            return null;
        }

    }

    /**
     * 注册设备号
     */
    public void regDeviceNo() {
        new Thread(new Runnable() {

            @Override
            public void run() {
                RegOrCancelDeviceNoInvokeItem item = new RegOrCancelDeviceNoInvokeItem(false);
                HttpRequestAsyncTaskQueue.getInstance().AddTask(new HttpTextAsyncTask(item).SetRequestType(HttpRequestType.SERVER_ONLY),
                        new OnHttpRequestTextListener() {

                            @Override
                            public void OnFail(boolean isCache, String reason) {
                            }

                            @Override
                            public void OnProgress(long total_bytes, long downloaded_bytes) {
                            }

                            @Override
                            public void OnSuccess(HttpInvokeItem item, boolean isCache, String cacheFilePath) {

                            }
                        });

            }
        }).start();
    }

    /**
     * 添加activity方法、将所有打开的页面保存在集合中。退出APP时kill所有页面
     *
     * @param mActivity 类名
     */
    public void addActivity(Activity mActivity) {
        for (int i = 0, size = activityList.size(); i < size; i++) {
            if (activityList.get(i) == mActivity) {
                return;
            }
        }
        activityList.add(mActivity);
    }

    /**
     * 移除某个activity方法
     */
    public void removeActivity(Activity mActivity) {
        for (int i = 0, size = activityList.size(); i < size; i++) {
            if (activityList.get(i) == mActivity) {
                activityList.remove(i);
                break;
            }
        }
    }

    /**
     * 退出整个app时，kill所有activity
     */
    public void ClearAllActivity() {
        for (int i = 0, size = activityList.size(); i < size; i++) {
            if (activityList.get(i) != null) {
                activityList.get(i).finish();
            }
        }
        activityList.clear();
    }

    public void initSmallVideo(Context context) {
        String path = com.qiyunxin.android.http.common.SystemUtil.GetExternalStorageDir() + getPackageName() + "/video/";
        VCamera.setVideoCachePath(path);
        // 开启log输出,ffmpeg输出到logcat
        VCamera.setDebugMode(false);
        // 初始化拍摄SDK，必须
        VCamera.initialize(context);
    }
}
